package nautilus.moneykeeper.dao;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import nautilus.moneykeeper.dto.Account;
import nautilus.moneykeeper.dto.Transaction;

public class DataFileUtils {
	
	public static boolean exportTransactionsToCSV(ArrayList<Transaction> trans, 
			String filePath) throws IOException{
		FileWriter fw = null;
		String dataLine = "";
		Transaction tr;
		try{
			fw = new FileWriter(filePath);
			BufferedWriter bw = new BufferedWriter(fw);
			dataLine = "Id,Amount,Account,Image,Category,Datetime,Description\n";
			bw.write(dataLine);
			for(int i=0; i<trans.size(); i++){
				tr = trans.get(i);
				dataLine = "" + tr.getId() + "," + tr.getAmount() + "," + tr.getAccount().getId() + 
						",\"" + tr.getImage() + "\"," + tr.getCategory().getId() + 
						",\"" + tr.getDatetime().toString() + "\",\"" + tr.getDescription() + "\"\n";
				bw.write(dataLine);
			}
			bw.flush();
			return true;
		}catch(IOException ex){
			return false;
		}
		finally{
			if(fw != null)
				fw.close();
		}
	}
	
	public static boolean exportAccountsToCSV(ArrayList<Account> accs,
			String filePath) throws IOException{
		FileWriter fw = null;
		String dataLine = "";
		Account ac;
		try{
			fw = new FileWriter(filePath);
			BufferedWriter bw = new BufferedWriter(fw);
			dataLine = "Id,Balance,Type,Datetime,Description\n";
			bw.write(dataLine);
			for(int i=0; i<accs.size(); i++){
				ac = accs.get(i);
				dataLine = "" + ac.getId() + "," + ac.getBalance() + "," + ac.getType().getId() + 
						",\"" + ac.getDateTime().toString() + "\",\"" + ac.getDescription() + "\"\n";
				bw.write(dataLine);
			}
			bw.flush();
			return true;
		}catch(IOException ex){
			return false;
		}
		finally{
			if(fw != null)
				fw.close();
		}
	}
}
